﻿var uk = require('./uk/uk.js');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
var path = require('path');

var dbip = '127.0.0.1';
//var dbip = 'gate.4kb.cc';
var dbport = 26379;
var dboption = {auth_pass:'dwerjkdsjfiwerwere~~'};
var netport = 3000;

/** 欢迎语 */
app.get('/', function(req, res){
	res.sendFile(path.resolve(__dirname,'./../client/index.html'));
});

// app.use('/assets',express.static(path.resolve(__dirname,'./../client/assets')))
// app.use('/css',express.static(path.resolve(__dirname,'./../client/css')))
// app.use('/fonts',express.static(path.resolve(__dirname,'./../client/fonts')))
// app.use('/js',express.static(path.resolve(__dirname,'./../client/js')))
app.use(express.static(path.resolve(__dirname,'./../client')))

/*
    连接redis数据库，createClient(port,host,options);
    如果REDIS在本机，端口又是默认(6379)，直接写createClient()即可
    redis.createClient() = redis.createClient(6379, '127.0.0.1', {})
*/
uk.db = redis.createClient(dbport,dbip,dboption);
uk.db.on('connect',on_db_initialized);
uk.db.on('error',function(errmsg){
    console.log('dberror:',errmsg);
});

function on_db_initialized(err){
    if(err){
        console.log('db connect failed:',err);
        return;
    }
    console.log('db connect success');

    if(!uk.hall.initialize()){
        return;
    }

    console.log('net initialize...');
    io.on('connection', function(socket){
        console.log('aaaa');
        /** 进入 */
        uk.hall.on_connect(socket);
        /** 离开 */
        socket.on('disconnect', function(){ uk.hall.on_disconnect(socket);});
    });

    server.listen(netport, function(){
        console.log('net initialize done,listening on *:'+netport);
    });
}

process.on('SIGINT', function() {
  console.log('server shutdown.....');
  uk.hall.shutdown(function(){
	console.log('server shutdown finish!');
	  process.exit(0);
  });
});